#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAXLINE 100

int main(void)
{
    int server_len, client_len;
    time_t ticks;
    int listenfd, connfd;
    struct sockaddr_in server_addr, client_addr;
    char buff[MAXLINE];
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    //server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    server_addr.sin_port = htons(8000);
    server_len = sizeof(server_addr);
	ticks = time(NULL);

    fprintf(stdout, "addr:%s\t bind:%d\t time:%s\n", inet_ntoa(server_addr.sin_addr), htons(8000), ctime(&ticks));

    bind(listenfd, (struct sockaddr *)&server_addr, server_len);
    listen(listenfd, 5);

    int conn_no = 1;
    for (; ;) {
		client_len = sizeof(client_addr);
		connfd = accept(listenfd, (struct sockaddr *)&client_addr, &client_len);
		ticks = time(NULL);
		char *c_time = ctime(&ticks);
		snprintf(buff, sizeof(buff), "%24s\r\n", c_time);
		write(connfd, buff, strlen(buff));
		fprintf(stdout, "connection(%d) from: %s, port: %d, at: %s\n", conn_no++,
				inet_ntop(AF_INET, &client_addr.sin_addr, buff, sizeof(buff)),
				ntohs(client_addr.sin_port), c_time);

		close(connfd);

    }
    exit(0);
}
